package com.lhm.controller;


import com.lhm.entity.MyUser;
import com.lhm.service.LargeFileService;
import com.lhm.service.UserService;

import com.lhm.tool.RespJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/api/fore/user")
public class UserForeController {

    @Autowired
    LargeFileService largeFileService;
    @Autowired
    UserService userService;

    //根据 getUser 拿到Token相应的登录用户的账号
    public static Object getUser(){
        Object object = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return object;
    }
    //更新密码成功
    @PostMapping("/updatePwd")
    public Map<String, Object> updatePwd(String pwd) {
        Map<String, Object> map = new HashMap();
        MyUser mu= (MyUser) getUser();//根据myuser 拿到Token相对应的id
        int uid = mu.getId();
        if (uid == -1) {
            return RespJson.pack(401, "未登录 ...", "");
        } else {
            map.put("id", uid);
            map.put("password", pwd);
           userService.update(map);
            return RespJson.pack(200, "更新密码成功", "");
        }
    }

    //更新用户信息成功
    @PostMapping("/updateInfo")
    public Map<String, Object> updateInfo(String nickname, String phone) {
        Map<String, Object> map = new HashMap();
        MyUser mu= (MyUser) getUser();//根据myuser 拿到Token相对应的id
        int uid = mu.getId();
        if (uid == -1){
            return RespJson.pack(401, "未登录 ...", "");
        } else {
            map.put("id", uid);
            map.put("nickname", nickname);
            map.put("phone", phone);
            userService.update(map);
            return RespJson.pack(200, "更新用户信息成功", "");
        }
    }

    /**
     * 自动转换日期类型的字段格式
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }
}
